#!/usr/bin/php

<?php

$opt = getopt("r:");
$rel = isset($opt['r']) ? intval($opt['r']) : '1';

$arch = trim(shell_exec("arch"));

if ($arch != "x86_64") {
    die("The architecture of the operating system does not support: $arch");
}

$basedir = realpath(__DIR__.'/../..');

$cmd = "cd $basedir/deps/redis\n
    make\n
    cp -rp ./src/redis-server $basedir/bin/lesskeeper-store ";
shell_exec($cmd);

$verctn = file_get_contents($basedir."/src/version.go");
if (!preg_match("/VERSION\ +string\ +\=\ +\"(.*)\"/", $verctn, $mat)) {
    die("Can not get VERSION");
}
$ver = $mat[1];

$pkgname = "lesskeeper";

$cmd = "rm -rf /tmp/{$pkgname}
mkdir -p /tmp/{$pkgname}/DEBIAN
cp $basedir/misc/debian/postinst /tmp/{$pkgname}/DEBIAN/postinst
cp $basedir/misc/debian/postrm /tmp/{$pkgname}/DEBIAN/postrm
cp $basedir/misc/debian/preinst /tmp/{$pkgname}/DEBIAN/preinst
cp $basedir/misc/debian/prerm /tmp/{$pkgname}/DEBIAN/prerm
";
shell_exec($cmd);


$file = "{$basedir}/misc/debian/control";
$control = file_get_contents($file);
$mat = array(
    "/Version:\ +(.*?)\n/",
    "/Architecture:\ +(.*?)\n/",
);
$rep = array(
    "Version: {$ver}-{$rel}\n",
    "Architecture: amd64\n",
);
$control = preg_replace($mat, $rep, $control);
file_put_contents("/tmp/{$pkgname}/DEBIAN/control", $control);


$cmd = "
mkdir -p /tmp/{$pkgname}/opt/less/keeper/bin
cp $basedir/bin/* /tmp/{$pkgname}/opt/less/keeper/bin/

mkdir -p /tmp/{$pkgname}/etc/init.d
cp $basedir/misc/debian/init.d-scripts /tmp/{$pkgname}/etc/init.d/lesskeeper
chmod +rx /tmp/{$pkgname}/etc/init.d/lesskeeper

mkdir -p /tmp/{$pkgname}/opt/less/keeper/etc
cp $basedir/misc/redis/redis.conf /tmp/{$pkgname}/opt/less/keeper/etc/redis.conf
cp $basedir/misc/keeper/keeper.json /tmp/{$pkgname}/opt/less/keeper/etc/keeper.json

mkdir -p /tmp/{$pkgname}/opt/less/keeper/var

dpkg -b /tmp/{$pkgname}/ ~/{$pkgname}_{$ver}-{$rel}_d6_amd64.deb

rm -rf /tmp/{$pkgname}";

shell_exec($cmd);

exit(0);
